<?php


namespace Leroi\VideoTools\Logic;


use Leroi\VideoTools\Enumerates\UserGentType;
use Leroi\VideoTools\Utils\CommonUtil;

class HaoKanLogic extends Base
{
    private $contents;

    public function setContents()
    {
        $client = new \GuzzleHttp\Client();
        $response = $client->request('GET', $this->url,['headers'=>[
            'Connection'=>'keep-alive',
            'User-Agent'=>UserGentType::ANDROID_USER_AGENT
        ]]);
        $body = $response->getBody();
        if ($body instanceof \GuzzleHttp\Psr7\Stream) {
            $body = $body->getContents();
        }
        $contents = htmlspecialchars_decode($body);
        $contents = str_replace(' ','',$contents);
        preg_match('/window\.\_\_PRELOADED\_STATE\_\_\=(\{\"\S+\})\;document\.querySelector/iu',$contents,$match);
        $contents = $match[1]?$match[1]:'{}';
        $this->contents = json_decode($contents,true);
    }

    /**
     * @return mixed
     */
    public function getContents()
    {
        return $this->contents;
    }

    /**
     * @return mixed
     */
    public function getUrl()
    {
        return $this->url;
    }

    public function getVideoUrl()
    {
        $clarityUrls = isset($this->contents['curVideoMeta']['clarityUrl'])?$this->contents['curVideoMeta']['clarityUrl']:[];
        $clarityUrls = is_array($clarityUrls)?$clarityUrls:[];
        $url = isset($this->contents['curVideoMeta']['playurl'])?$this->contents['curVideoMeta']['playurl']:'';
        foreach ($clarityUrls as $clarityUrl){
            if (isset($clarityUrl['url'])&&is_string($clarityUrl['url'])&&(strlen($clarityUrl['url'])>4)){
                $url = $clarityUrl['url'];
            }
        }
        return  CommonUtil::getData($url);
    }

    public function getVideoImage()
    {
        return  CommonUtil::getData(isset($this->contents['curVideoMeta']['poster'])?$this->contents['curVideoMeta']['poster']:'');
    }

    public function getVideoDesc()
    {
        return  CommonUtil::getData(isset($this->contents['curVideoMeta']['title'])?$this->contents['curVideoMeta']['title']:'');
    }

    public function getUsername()
    {
        return  CommonUtil::getData(isset($this->contents['curVideoMeta']['source_name'])?$this->contents['curVideoMeta']['source_name']:'');
    }

    public function getUserPic()
    {
        return  CommonUtil::getData(isset($this->contents['curVideoMeta']['avatar'])?$this->contents['curVideoMeta']['avatar']:'');
    }
}
